package com.bit.net;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;

/**
 * 服务
 * <p>
 * 开启服务
 * </p>
 *
 * @since 2018/10/10
 */
@Slf4j
public class BaseNettyClient {

    private String host;

    private Integer port;

    private ChannelInitializer channelInitializer;

    public BaseNettyClient(String host, Integer port, ChannelInitializer channelInitializer) {
        this.host = host;
        this.port = port;
        this.channelInitializer = channelInitializer;
    }

    protected void start0() throws Exception {
        EventLoopGroup worker = new NioEventLoopGroup();
        try {
            //辅助启动类
            Bootstrap bootstrap = new Bootstrap();
            //设置线程池
            bootstrap.group(worker);
            //设置socket工厂
            bootstrap.channel(NioSocketChannel.class);
            //设置管道
            bootstrap.handler(channelInitializer);
            //发起异步连接操作
            ChannelFuture futrue = bootstrap.connect(new InetSocketAddress(host, port)).sync();
            futrue.channel().closeFuture().sync();
        } finally {
            //优雅的退出，释放NIO线程组
            worker.shutdownGracefully();
        }
    }


    public void start() throws Exception {
        new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    start0();
                } catch (Exception e) {
                    log.warn("Start client server cause an error.", e);
                }
            }
        }, "client-starter-thread").start();
    }
}
